import json
import os
from weibosender.utils.path_utils import PathUtils


class GatherPageConfig:
    _config_file = PathUtils.root_path + '/gatherPageRecord.json'

    @staticmethod
    def get_current_gather_page():
        if not os.path.exists(GatherPageConfig._config_file) or \
                not os.path.isfile(GatherPageConfig._config_file):
            return None

        try:
            file_object = open(GatherPageConfig._config_file, 'r', encoding='utf-8')
            file_content = file_object.read()
        except Exception as e:
            print('配置文件错误：读取失败，采取页码记录配置，%s' % e)
            return None
        finally:
            file_object.close()

        if not file_content:
            return None
        try:
            json_obj = json.loads(file_content)
        except Exception as e:
            GatherPageConfig.write('')
            return None

        return json_obj

    @staticmethod
    def write(json_string):
        try:
            file_object = open(GatherPageConfig._config_file, 'w', encoding='utf-8')
            file_object.write(json_string)
        except Exception as e:
            print('写入文件失败：采集页码记录配置，%s' % e)
        finally:
            file_object.close()

